package other.edan.erp.k3;


import com.alibaba.fastjson.JSONObject;
import com.rkhd.platform.sdk.ScheduleJob;
import com.rkhd.platform.sdk.api.annotations.RequestMethod;
import com.rkhd.platform.sdk.api.annotations.RestApi;
import com.rkhd.platform.sdk.api.annotations.RestMapping;
import com.rkhd.platform.sdk.data.model.K3Department__c;
import com.rkhd.platform.sdk.data.model.SnCode__c;
import com.rkhd.platform.sdk.data.model.SyncConfig__c;
import com.rkhd.platform.sdk.exception.AsyncTaskException;
import com.rkhd.platform.sdk.exception.ScriptBusinessException;
import com.rkhd.platform.sdk.log.Logger;
import com.rkhd.platform.sdk.log.LoggerFactory;
import com.rkhd.platform.sdk.param.ScheduleJobParam;
import com.rkhd.platform.sdk.service.FutureTaskService;
import com.rkhd.platform.sdk.service.XoqlService;
import com.rkhd.platform.sdk.task.FutureTask;
import other.edan.erp.apitool.EdanK3Utils;
import other.edan.erp.utils.HCXObjectService;
import other.edan.erp.utils.ResultBody;
import other.edan.erp.utils.ResultVo;

import java.util.*;
import java.util.stream.Collectors;


/**
 * @Description 同步k3产品部门
 * @Author 黎炎松
 * 2024-12-12 13:56
 */
public class SyncDepart extends SyncSuper implements ScheduleJob, FutureTask {
    private static XoqlService xoqlService = XoqlService.instance();
    private static final Logger LOGGER = LoggerFactory.getLogger();
    private static String LOGGER_MSG = "同步K3部门编码 ==> ";

    // 执行定时任务
    @Override
    public void execute(ScheduleJobParam scheduleJobParam) {
        LOGGER.debug(LOGGER_MSG + " 执行定时任务开始");
        try {
            String messageId = FutureTaskService.instance().addFutureTask(getClass(), "");
            LOGGER.info(LOGGER_MSG + "异步ID:" + messageId);
        } catch (Exception e) {
            LOGGER.error(LOGGER_MSG + " ----- 发生异常：" + e.getMessage());
        }
    }

    // 执行异步函数
    @Override
    public void execute(String s) throws ScriptBusinessException {
        startSyncDepart();
    }

    
    public static void main(String[] args) {
        HCXObjectService.isLocal = true;
        new SyncDepart().startSyncDepart();
    }

    /**
     * 开始同步SN码
     */
    public ResultVo startSyncDepart() {
        try {
            LOGGER.debug(LOGGER_MSG + "处理开始");

            // 从数据配置表中获取数据
            SyncConfig__c syncConfig = getSyncConfig("k3_BM");

            // 设置参数
            Map<String, Object> paramsMap = new HashMap<>();
            paramsMap.put("page", "1");
            paramsMap.put("pageSize", "500");
            LOGGER.debug(LOGGER_MSG + " paramsMap: " + paramsMap);

            // 发送请求获取数据
            // todo (去除token)
            ResultBody response = EdanK3Utils.sendGet(paramsMap, EdanK3Utils.GET_DEPART, "");
            if (!Objects.equals(response.getCode(), "200")) {
                LOGGER.debug(LOGGER_MSG + "查询k3数据异常: " + response.getMessage());
                return ResultVo.error("查询k3数据异常: " + response.getMessage());
            }

            // 获取数据 判断是否有值
            JSONObject result = (JSONObject) response.getResult();
            List<JSONObject> k3DataList = JSONObject.parseArray(result.getJSONArray("deptInfos").toJSONString(), JSONObject.class);
            LOGGER.debug(LOGGER_MSG + "查询返回的数据: " + k3DataList.size());
            if (k3DataList.size() <= 0) {
                LOGGER.debug(LOGGER_MSG + "暂无需要处理的数据");
                // 同步修改配置表
                upSyncConfig(syncConfig);
                return ResultVo.success();
            }

            // 获取系统中存在的数据
            Map<String, Long> crmDataMap = getCrmDataMap("k3depart", "fInterId", k3DataList);

            // 获取新增、修改的数据
            List<K3Department__c> crmAddList = new ArrayList<>(); // CRM新增集合
            List<K3Department__c> crmUpList = new ArrayList<>(); // CRM修改集合
            for (JSONObject k3data : k3DataList) {
                // 处理数据
                K3Department__c depart = new K3Department__c();
                String fInterId = k3data.getString("fInterId");
                depart.setName(k3data.getString("fName"));

                // 判断系统中是否存在，存在则更新
                if (crmDataMap.containsKey(fInterId)) {
                    depart.setId(crmDataMap.get(fInterId));
                    crmUpList.add(depart);
                } else {
                    depart.setDepartId__c(fInterId);
                    depart.setEntityType(3590486502972063L);
                    crmAddList.add(depart);
                }

                // 进行新增、更新
                if (crmAddList.size() >= 100) {
                    HCXObjectService.updateBatch(crmAddList);
                    crmAddList.clear();
                }
                if (crmUpList.size() >= 100) {
                    HCXObjectService.updateBatch(crmUpList);
                    crmUpList.clear();
                }
            }

            // 进行批量新增、更新
            HCXObjectService.insertBatch(crmAddList);
            HCXObjectService.updateBatch(crmUpList);

            // 更新同步配置
            upSyncConfig(syncConfig);

            LOGGER.debug(LOGGER_MSG + "处理成功");
            return ResultVo.success();
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.debug(LOGGER_MSG + "处理异常:" + e.getMessage());
            return ResultVo.error("处理异常: " + e.getMessage());
        }
    }



}
